<template>
  <div class="app-container">
    <!-- 系统监听 -->
    <el-dialog
      id="sysJtDialog"
      title="节点监控"
      :visible.sync="sysDialogVisibles"
      width="800px"
      :before-close="sysDialogClose"
    >
      <div class="bdBody">
        <div>
          <el-row class="qin">
            <el-col :span="1" class="card-box" />
            <el-col :span="3" class="card-box"> 节点名称 : </el-col>
            <el-col :span="8" class="card-box">
              {{ rowData.nodeName }}
            </el-col>
            <el-col :span="3" class="card-box"> 节点IP : </el-col>
            <el-col :span="6" class="card-box">
              {{ rowData.nodeIp }}
            </el-col>
            <el-col :span="3" class="card-box" />
          </el-row>
        </div>
        <el-row>
          <el-col :span="6" class="card-box">
            <div class="div1">
              <percentage ref="percentage" />
              <p>CPU使用率</p>
            </div>
            <div class="div1">
              <percentage ref="percentage2" />
              <p>内存使用率</p>
            </div>
            <div class="div1">
              <percentage ref="percentage3" />
              <p>磁盘使用率</p>
            </div>
          </el-col>

          <el-col :span="18" class="card-box">
            <div ref="commandstats4" style="height: 200px" />
          </el-col>
          <el-col :span="18" class="card-box">
            <div ref="commandstats5" style="height: 200px" />
          </el-col>
          <el-col :span="18" class="card-box">
            <div class="diskListBox">
              <ul>
                <li>磁盘</li>
                <li>使用量</li>
                <li>总量</li>
                <li>剩余容量</li>
              </ul>

              <ul v-for="(item, i) in nodeDiskList" :key="i">
                <li>{{ item.name }}</li>
                <li>
                  {{ item.use }} <span v-show="item.use != '加载中...'">G</span>
                </li>
                <li>
                  {{ item.total }}
                  <span v-show="item.use != '加载中...'">G</span>
                </li>
                <li>
                  {{ item.surplus
                  }}<span v-show="item.use != '加载中...'">G</span>
                </li>
              </ul>
            </div>
          </el-col>
        </el-row>
      </div>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="dialogVisible = false">取 消</el-button> -->
        <el-button @click="sysDialogVisibles = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { nodeSystemInfo } from '@/api/monitor/node'
import * as echarts from 'echarts'
import percentage from '@/views/components/flowChart/percentage'

export default {
  name: 'NodeIndex',
  components: {
    percentage
  },
  props: {
    sysDialogVisible: Boolean
  },
  data() {
    return {
      sysDialogVisibles: false,
      loading: '',
      nodeCpu: 0,
      diskUsed: 0,
      nodeMUsed: 0,
      nodeDiskList: [
        {
          name: '加载中...',
          use: '加载中...',
          total: '加载中...',
          surplus: '加载中...'
        }
      ],
      nodeRecv: [],
      nodeSent: [],
      newNodeRecvArr: [],
      newNodeSentArr: [],
      option: {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['宽带入']
        },
        title: {
          text: '内存使用',
          subtext: 'KB'
        },
        xAxis: {
          type: 'time',
          show: false,
          boundaryGap: false,
          data: []
        },
        color: ['#409eff'],
        yAxis: {
          type: 'value',
          // scale:true,
          max: function(value) {
            let num
            if (value.max < 100) {
              num = value.max + 5
            } else if (value.max > 100 && value.max < 1000) {
              num = value.max + 100
            } else {
              num = value.max + 200
            }

            if (num < 10) {
              num = 10
            } else {
              if (num % 10) {
                num = num + 10 - (num % 10)
              }
            }
            return Math.ceil(num)
          }
        },
        series: [
          {
            data: [],
            type: 'line'
          }
        ]
      },
      rowData: {
        nodeIp: '',
        nodeName: ''
      },
      optionPressure: {
        series: [
          {
            type: 'gauge',
            axisLine: {
              lineStyle: {
                width: 10,
                color: [
                  [0.3, '#a0cfff'],
                  [0.7, '#409eff'],
                  [1, '#F56C6C']
                ]
              }
            },
            pointer: {
              itemStyle: {
                color: 'auto'
              }
            },
            axisTick: {
              distance: -10,
              length: 0,
              lineStyle: {
                color: '#fff',
                width: 2
              }
            },
            splitLine: {
              distance: -10,
              length: 5,
              lineStyle: {
                color: '#fff',
                width: 3
              }
            },
            axisLabel: {
              color: 'auto',
              distance: 20,
              fontSize: 12
            },
            detail: {
              valueAnimation: true,
              formatter: '{value} %',
              color: 'auto',
              offsetCenter: [0, '70%']
            },
            data: [
              {
                value: 0
              }
            ]
          }
        ]
      }
    }
  },
  created() {},
  mounted() {},
  methods: {
    // 查看
    showHandle(row) {
      this.rowData = row
      if (row.nodeStatus == 0) {
        this.sysDialogVisibles = false
        this.$message.error('错误，必须是在线状态才可查看监控')
        return false
      }

      this.loading = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      var vue = this
      setTimeout(() => {
        if (vue.loading) {
          vue.loading.close()
        }
      }, 9000)

      this.nodeCpu = 0
      this.diskUsed = 0
      this.nodeMUsed = 0
      this.nodeRecv = []
      this.nodeSent = []
      this.newNodeRecvArr = []
      this.newNodeSentArr = []
      this.nodeDiskList = [
        {
          name: '加载中...',
          use: '加载中...',
          total: '加载中...',
          surplus: '加载中...'
        }
      ]

      this.option.xAxis.data = []

      if (!row.nodeIp) {
        this.sysDialogVisibles = false
        this.$message.error('节点IP参数错误')
        return false
      }
      if (!row.haPort) {
        this.sysDialogVisibles = false
        this.$message.error('节点端口参数错误')
        return false
      }
      this.getNodeSystemInfoOne(row)
    },
    // 第一次连接
    getNodeSystemInfoOne(row) {
      nodeSystemInfo({
        nodeIp: row.nodeIp, // '192.168.2.32',
        haPort: row.haPort // '6099',
      }).then((response) => {
        if (this.loading) {
          this.loading.close()
        }
        this.sysDialogVisibles = true
        if (response.data) {
          this.showCharts(response.data, row)
        } else {
          this.sysDialogVisibles = false
          this.$message.error('错误，暂未查询到系统参数')
          return false
        }
      })
    },
    getNodeSystemInfo(row) {
      this.getNodeDiskInfoFn(row.id)
      nodeSystemInfo({
        nodeIp: row.nodeIp, // '192.168.2.32',
        haPort: row.haPort // '6099',
      })
        .then((response) => {
          if (this.loading) {
            this.loading.close()
          }

          if (response.data) {
            this.showCharts(response.data, row)
          } else {
            this.sysDialogVisibles = false
            this.$message.error('此节点，系统参数为空')
            return false
          }
        })
        .catch((res) => {
          this.loading.close()
        })
    },
    showCharts(resData, row) {
      var vue = this
      this.$nextTick(() => {
        const timeData = vue.option.xAxis.data
        if (timeData.length > 10) {
          timeData.shift()
        }
        // timeData.push(this.getNowTime())
        // timeData.push('')
        // vue.option.xAxis.data = timeData;
        this.$refs.percentage.init(Number(resData.nodeCpu))
        this.$refs.percentage2.init(
          Number(
            ((resData.nodeMemUsed / resData.nodeMemTotal) * 100).toFixed(1)
          )
        )
        this.$refs.percentage3.init(
          Number(
            ((resData.nodeDiskUsed / resData.nodeDiskTotal) * 100).toFixed(1)
          )
        )

        this.buildeEchearsData('commandstats4', 'nodeRecv', resData)
        this.buildeEchearsData('commandstats5', 'nodeSent', resData)

        if (this.sysDialogVisibles) {
          if (this.sysDialogVisiblesTime) {
            clearTimeout(this.sysDialogVisiblesTime)
          }
          this.sysDialogVisiblesTime = setTimeout(() => {
            this.getNodeSystemInfo(row)
          }, 3000)
        }
      })
    },
    buildeEchearsData(commandstats, nodeType, resData) {
      var vue = this
      this.commandstats = echarts.getInstanceByDom(this.$refs[commandstats]) // 有的话就获取已有echarts实例的DOM节点。
      if (this.commandstats == null) {
        // 如果不存在，就进行初始化。
        this.commandstats = echarts.init(this.$refs[commandstats], 'macarons')
      }

      let isBroadband = ''
      if (nodeType == 'nodeRecv') {
        vue.option.title.text = '带宽入'
        isBroadband = true
        var newArr = vue.newNodeRecvArr
      } else if (nodeType == 'nodeSent') {
        vue.option.title.text = '带宽出'
        isBroadband = true
        var newArr = vue.newNodeSentArr
      }

      let nodeData = 0
      var now = new Date().getTime()
      if (isBroadband) {
        if (vue.$data[nodeType].length > 1) {
          const len = newArr.length

          nodeData = resData[nodeType] - newArr[len - 1]

          newArr.push(resData[nodeType])
        } else {
          newArr.push(resData[nodeType])
          // vue.$data[nodeType].push({"name":now,"value":0})
        }
      }

      if (vue.$data[nodeType].length > 10) {
        vue.$data[nodeType].shift()
      }

      if (newArr.length > 10) {
        newArr.shift()
      }

      const kbData = this.data_processing(nodeData)

      vue.$data[nodeType].push({ name: now, value: [now, kbData] })

      vue.option.series[0].data = vue.$data[nodeType]

      if (nodeType == 'nodeRecv') {
        vue.option.title.subtext = this.page_data_processing(kbData)
      } else if (nodeType == 'nodeSent') {
        vue.option.title.subtext = this.page_data_processing(kbData)
      }

      vue.commandstats.setOption(vue.option)
    },
    // 获取当前时间
    getNowTime() {
      const now = new Date()
      const _minute =
        now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes()
      const _second =
        now.getSeconds() < 10 ? '0' + now.getSeconds() : now.getSeconds()
      // 		return {
      // 			name: now.toString(),
      // 			value: [
      // 				[now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'),
      // 				Math.round(value)
      // 			]
      // 		};
      return _minute + ':' + _second
    },
    // 数据处理
    data_processing(limit) {
      var size = ''
      //             if( limit < 0.1 * 1024 ){ //如果小于0.1KB转化成B
      //                 size = limit.toFixed(2) + "B";
      //             }else if(limit < 0.1 * 1024 * 1024 ){//如果小于0.1MB转化成KB
      //                 size = (limit / 1024).toFixed(2) + "KB";
      //             }else if(limit < 0.1 * 1024 * 1024 * 1024){ //如果小于0.1GB转化成MB
      //                 size = (limit / (1024 * 1024)).toFixed(2) + "MB";
      //             }else{ //其他转化成GB
      //                 size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
      //             }
      size = (limit / 1024 / 2).toFixed(2)

      var sizestr = size + ''
      var len = sizestr.indexOf('\.')
      var dec = sizestr.substr(len + 1, 2)
      if (dec == '00') {
        // 当小数点后为00时 去掉小数部分
        return sizestr.substring(0, len) + sizestr.substr(len + 3, 2)
      }
      if (isNaN(sizestr)) {
        sizestr = 0
      }
      return sizestr
    },
    // 页面显示kb 转换
    page_data_processing(limit) {
      var size = ''
      var limit = Number(limit) * 1024
      if (limit < 0.1 * 1024) {
        // 如果小于0.1KB转化成B
        size = limit.toFixed(2) + 'B'
      } else if (limit < 0.1 * 1024 * 1024) {
        // 如果小于0.1MB转化成KB
        size = (limit / 1024).toFixed(2) + 'KB'
      } else if (limit < 0.1 * 1024 * 1024 * 1024) {
        // 如果小于0.1GB转化成MB
        size = (limit / (1024 * 1024)).toFixed(2) + 'MB'
      } else {
        // 其他转化成GB
        size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
      }

      return size
    },
    // 关闭
    sysDialogClose() {
      this.sysDialogVisibles = false
    },
    // 获取磁盘使用量
    getNodeDiskInfoFn(id) {
      var vue = this
      getNodeDiskInfo({ id: id }).then((response) => {
        vue.nodeDiskList = []
        if (response.data) {
          vue.nodeDiskList = vue.handleDataList(response.data)
        } else {
          this.$message({
            message: '未查询到 节点 磁盘信息',
            type: 'warning'
          })
        }
      })
    },
    // 处理磁盘数据
    handleDataList(json) {
      var jsonData = []
      for (const k in json) {
        var arr = json[k].split(',')
        jsonData.push({
          name: k,
          use: arr[0],
          total: arr[1],
          surplus: (arr[1] - arr[0]).toFixed(2),
          class: ''
        })
      }

      return jsonData
    }
  }
}
</script>
<style scoped="scoped">
.div1 {
  text-align: center;
  margin-top: 20px;
}
ul,
li {
  list-style: none;
}

.qin {
  color: #30acba;
}

.diskListBox {
  background: #30acba;
  color: #ffffff;
  border-radius: 10px;
  min-height: 81px;
}
.diskListBox > ul {
  display: flex;
  width: 100%;
  padding: 5px;
}

.diskListBox ul,
.diskListBox li {
  text-align: center;
  flex: 1;
  margin: 0;
  list-style: none;
}
</style>

<style>
#sysJtDialog .el-dialog__body {
  padding: 10px 20px 5px;
}
</style>
